import { getCookie } from './getCookie.js';
import { ajax } from './Promise_AJAX.js';
let select = document.querySelector('.timeSelect'),
    main = document.querySelector('main > .content>.main'),
    {token} = getCookie(),
    flag,//点击状态开关
    show_status//场次预约状态
// 重新登陆
if((token ==undefined)||(token=='')){
    alert('请登录')
    location.href='./index.html' 
}
// 
;(async ()=>{
    // 获取预约时间列表  [{day_time: '2021-10-20'},...]
    let TimeList =await ajax(`http://newshopapi.0melon0.cn/api/f_user/chooselist?token=${token}`),
        day//['2021', '10', '23']
    TimeList.result.list.forEach(val => {
        day = val.day_time.split('-')//['2021', '10', '21']
        select.innerHTML +=`<option value="${val.day_time}">${day[1]}月${day[2]}日</option>`
    })
    // 查询某天场次  [{day_time: '2021-10-21', show_id: 1, show_name: '09:00-12:00'},...]
    let getTimeName = await ajax(`http://newshopapi.0melon0.cn/api/f_user/chooseday?token=${token}&day_time=${select.value}`)
    function Fn(getTimeName) {
        day = select.value.split('-')
        // 页面插入场次信息
        getTimeName.result.list.forEach((val,idx)=>{
            // console.log(val)//{day_time: '2021-10-21', show_id: 1, show_name: '09:00-12:00'}
            let { show_id, day_time,show_name}=val,
                [start_time,end_time] = [show_name.slice(0,5),show_name.slice(6,11)] 
            // 获取某场次时间戳函数
            function stTimeFn(Time){
                return new Date(`${day[0]} ${day[1]} ${day[2]} ${Time}:00`).getTime()
            }
            let z = (Date.now() >=stTimeFn(start_time)) && (Date.now() <=stTimeFn(end_time))
            // 判断状态
            z ? ([show_status,flag] = ['不可预约',false]) : ([show_status,flag] = ['可预约',true])
            ;((Date.now() >=stTimeFn(start_time)))&&([show_status,flag] = ['不可预约',false])
            // 插入场次、状态信息函数
            function addData() {
                 let newP= document.createElement('p')
                 main.append(newP)
                 document.querySelectorAll('.main p')[idx].innerHTML=`<span>${show_name}</span><span class="bookBtn" data-id=${show_id}>${show_status}</span>`
                 // main.innerHTML +=`<p><span>${val.show_name}</span><span class="bookBtn" data-id=${idx+1}>${show_status}</span></p>`  //这样只能最后一个有点击事件
            }
            addData()
            // 判断是否能预约
            if(flag){
                setTimeout(()=>{
                // 点击预约  状态栏  第二个span
                document.querySelectorAll(".bookBtn")[idx].addEventListener('click',e=>{
                    let show_id=e.target.getAttribute('data-id'),
                        data= {"token":token, "day_time":day_time, "show_id":show_id}
                    ;(async () =>{
                        // 预约某天场次  {id: 5538, day_time: '2021-10-23', show_id: '3', name: 'zhub n', user_id: 440, …}
                        let book = await ajax(`http://newshopapi.0melon0.cn/api/f_user/bookday`,data,'POST')
                        document.cookie=`id=${book.result.id};`
                        document.cookie=`token=${token}`
                        document.cookie=`name=${book.result.name}`
                        document.cookie=`day_time=${day_time}`
                        document.cookie=`show_id=${show_id}`
                        document.cookie=`show_name=${show_name}`
                        location.href=`./appointmentOk.html`
                    })()
                })
            })
            }
        })
    }
    Fn(getTimeName)
    //下拉框状态改变时
    select.addEventListener('change',()=>{
       ;(async ()=>{
            // 查询某天场次
            getTimeName = await ajax(`http://newshopapi.0melon0.cn/api/f_user/chooseday?token=${token}&day_time=${select.value}`)
            main.innerHTML=''
            Fn(getTimeName)
        })()
    })
})()